package wms.service.repo;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import wms.dao.repo.WareHouseMapper;
import wms.dao.store.StoreSetMapper;
import wms.entity.WareHouse;

@Service
public class RepoServiceImpl implements RepoService {

	@Resource
	private WareHouseMapper repoMapper;
	
	@Resource
	private StoreSetMapper storeSetMapper;
	
	@Override
	public List<WareHouse> listAllWareHouse() throws Exception {
		return repoMapper.queryAll();
	}

	@Override
	public boolean txSaveRepo(WareHouse wareHouse) throws Exception {
		WareHouse repo = repoMapper.queryById(wareHouse.getRepoCode());
		if(repo != null) {
			throw new RuntimeException("该仓库已经存在,请勿重复添加");	
		}

		return repoMapper.txSave(wareHouse);
	}

	@Override
	public boolean txDeleteRepo(String repoCode) throws Exception {
		if (repoCode == null || !repoCode.startsWith("CK")) {
			throw new RuntimeException("该仓库不存在,无法删除!");
		}
		//判断该仓库是否存有物资 如果有拒绝删除
		//删除该仓库
		if (storeSetMapper.getStoreSet(null, repoCode) != null) 
			throw new RuntimeException("该仓库正在使用中, 无法完成删除!");
		return repoMapper.txDelete(repoCode);
	
	}

	@Override
	public boolean txModifyRepo(WareHouse wareHouse, String operator) throws Exception {
		WareHouse repo = repoMapper.queryById(wareHouse.getRepoCode());
		if (repo == null)
			throw new RuntimeException("该仓库不存在,无法修改!");
	
		wareHouse.setModifyBy(operator);
		wareHouse.setModifyDate(new Date(System.currentTimeMillis()));
		return repoMapper.txModify(wareHouse);
	}

	@Override
	public WareHouse getWareHouse(String repoCode) throws Exception {
		return repoMapper.queryById(repoCode);
	}

	@Override
	public boolean txClearRepo(String repoCode) throws Exception {
		WareHouse repo = repoMapper.queryById(repoCode);
		if (repo == null)
			throw new RuntimeException("该仓库不存在! 无法清理");
		//如果没有该库存信息, 直接跳过
		if (storeSetMapper.getStoreSet(null, repoCode) != null) 
			return false;
		return storeSetMapper.txDeleteStoreSet(null, repoCode);
	}

	@Override
	public int getTotalCount() throws Exception {
		return repoMapper.getTotalCount();
	}

}
